<template>
  <el-drawer with-header :visible.sync="open_scheduling" direction="rtl" size="35%" :show-close="false"
    :wrapperClosable="false">
    <!-- {{form}} -->
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="ml30">
          <div class="grid-content bg-purple-dark    text-size-23-w700  ">新增排课</div>

          <div class="grid-content bg-purple     text-size-16 mt20 text-gray  ">切换为日历模式可以单独选择日期</div>

        </div>

      </el-col>
      <el-col :span="12">
        <div class="classflex-end">
          <el-button v-if="type==1" style="width: 100px;margin-right: 20px;" @click="changge(1)">日历模式</el-button>
          <el-button v-if="type==2" style="width: 100px;margin-right: 20px;" @click="changge(2)">规则模式</el-button>
          <el-button @click="cancel" style="width: 100px;margin-right: 40px;">取消</el-button>

        </div>

      </el-col>
    </el-row>


    <el-form :hide-required-asterisk="true" ref="form" :model="form" :rules="rules_scheduing" label-width="80px">
      <el-divider style="width: 80%;"></el-divider>

      <div class="ml20 mr20">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排课班级" prop="classCourse" :disabled="nodisabled">
              <!-- <el-input v-model="form.className" placeholder="请输入课程" /> -->

              <el-select v-model="form.classCourse" placeholder="请选择课程" filterable @change="ChangeCourseName">
                <el-option v-for="dict in courseList" :key="dict.id" :label="dict.courseName" :value="dict.courseName">
                </el-option>

              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="排课班级" prop="className" :disabled="nodisabled">
              <el-select v-model="form.className" placeholder="请选择班级" filterable @change="ChangeClassName">
                <el-option v-for="dict in schoolclassList" :key="dict.id" :label="dict.className"
                  :value="dict.className">
                </el-option>

              </el-select>
            </el-form-item>


          </el-col>

        </el-row>
      </div>


      <!--    type_one_date_picker {{type_one_date_picker}}
      classWorkOut{{classWorkOut}}
      one_date_picker_data {{one_date_picker_data}} -->
      <div class="ml20">

        <div v-if="type==1">
          <el-form-item label="排课周期" prop="">


            <el-date-picker value-format="yyyy-MM-dd" v-model="type_one_date_picker" type="daterange"
              range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>

          </el-form-item>
          <el-form-item label="周几排课" prop="classWorkOut">


            <el-select v-model="classWorkOut" multiple placeholder="请选择周几排课" style="width: 360px;">
              <el-option v-for="dict in dict.type.week_day" :key="dict.value" :label="dict.label" :value="dict.value">
              </el-option>
            </el-select>


          </el-form-item>
          <el-form-item label="循环方式" prop="classCirculate">
            <el-select v-model="form.classCirculate" placeholder="请选择循环方式" style="width: 360px;">
              <el-option v-for="dict in dict.type.class_circulate" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>


        </div>
        <div v-if="type==2">
          <el-form-item label="排课日期" prop="">


            <el-date-picker ref="datesRef" type="dates" v-model="type_two_date_picker" :editable="false"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择一个或多个日期">
            </el-date-picker>

          </el-form-item>

          <div>您选择的日期为：{{type_two_date_picker}}</div>

        </div>


        <el-form-item label="开始时间" prop="classStart">

          <el-time-picker :value-format="pickerFormatText" :format="pickerFormatText" style="width: 360px;"
            v-model="form.classStart" :picker-options="{
                    selectableRange: '00:00:00 - 23:59:59', format: pickerFormatText
                  }" placeholder="开始时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="classFinish">
          <el-time-picker :value-format="pickerFormatText" :format="pickerFormatText" style="width: 360px;"
            v-model="form.classFinish" :picker-options="{
                    selectableRange: '00:00:00 - 23:59:59', format: pickerFormatText
                  }" placeholder="结束时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="课时数" prop="classHours">
          <el-input-number v-model="form.classHours" :min="1" :max="10" label="描述文字" controls-position="right">
          </el-input-number>
        </el-form-item>
        <el-form-item label="授课教师" prop="classTeacher">

          <el-select style="width: 350px;" multiple v-model="classTeacher" placeholder="请选择授课教师" filterable>
            <el-option v-for="dict in userList" :key="dict.userId" :label="dict.nickName" :value="dict.nickName">
            </el-option>
          </el-select>



        </el-form-item>
        <el-form-item label="考勤员" prop="classAttendant">
          <el-select style="width: 350px;" v-model="form.classAttendant" placeholder="请输入考勤员" filterable>
            <el-option v-for="dict in userList" :key="dict.userId" :label="dict.nickName" :value="dict.nickName">
            </el-option>

          </el-select>
        </el-form-item>
        <el-form-item label="上课教室" prop="classRoom">
          <el-select style="width: 350px;" v-model="form.classRoom" placeholder="请输入上课教室" filterable>
            <el-option v-for="dict in classroomList" :key="dict.userId" :label="dict.classroomName"
              :value="dict.classroomName">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
    </el-form>
    <el-divider></el-divider>
    <div class="ml20 mr20">
      <el-button type="primary" @click="submitForm" style="width: 100%;">立即创建</el-button>

    </div>
  </el-drawer>

</template>

<script>
  import {
    listScheduling,
    getScheduling,
    delScheduling,
    addScheduling,
    updateScheduling
  } from "@/api/scheduling/scheduling";
  import {
    listClassroom,
    getClassroom,
    delClassroom,
    addClassroom,
    updateClassroom
  } from "@/api/classroom/classroom";
  import {
    listUser,
    listUser2,
    getUser,
    delUser,
    addUser,
    updateUser,
    resetUserPwd,
    changeUserStatus,
    deptTreeSelect
  } from "@/api/system/user";
  import {
    listSchoolclass,
    getSchoolclass,
    delSchoolclass,
    addSchoolclass,
    updateSchoolclass
  } from "@/api/schoolclass/schoolclass";
  import {
    listOrderother,
    getOrderother,
    delOrderother,
    addOrderother,
    updateOrderother
  } from "@/api/orderother/orderother";

  import {
    listCourse,
    getCourse,
    delCourse,
    addCourse,
    updateCourse
  } from "@/api/course/course";
  export default {
    name: "AddSchedulingDrawer",
    dicts: ['class_circulate', 'week_day'],
    data() {
      return {
        pickerFormatText: 'HH:mm',
        type: 1,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        nodisabled: false,
        type_one_date_picker: [],
        type_two_date_picker: [],
        classWorkOut: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 课程表表格数据
        schedulingList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open_scheduling: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deptId: null,
          className: null,
          classCourse: null,
          classCapacity: null,
          classAskforleave: null,
          classNoyet: null,
          classWorkOut: null,
          classCirculate: null,
          classStart: null,
          classFinish: null,
          classHours: null,
          classTeacher: null,
          classAttendant: null,
          classRoom: null,
          classStudent: null,
          schedulingremark: null,
          schedulingremark2: null,
          schedulingremark3: null,
          schedulingremark4: null,
          schedulingremark5: null,
          schedulingremark6: null,
          schedulingremark7: null,
          schedulingremark8: null,
          schedulingremark9: null,
          schedulingremark10: null,
          classId: null,
          studyDate: null,
          week: null,
          state: null,
          reach: null,
          unreach: null,
          askforleave: null,
          attendance: null,
          totalConsumption: null
        },
        // 表单参数
        form: {
          classHours: 1,
          classCirculate: "每周循环"
        },
        // 表单校验
        rules: {},
        userList: [],
        classroomList: [],
        queryParamsTeacher: {},
        queryclassroomParams: {},
        queryParamsSchool: {},
        schoolclassList: [],
        queryParamsCourse: {},
        courseList: [],
        classTeacher: null,
        datepicker: [],
        result: null,
        one_date_picker_data: null,
        two_date_picker_data: null,
        rules_scheduing: {
          classCourse: [{
              required: true,
              message: '请输入课程名称',
              trigger: 'change'
            },

          ],
          // className: [{
          //   required: true,
          //   message: '请选择上课班级',
          //   trigger: 'change'
          // }],


          // remark: [{
          //     required: true,
          //     message: '请选择课程科目',
          //     trigger: 'change'
          //   }

          // ],
          classStart: [{
              required: true,
              message: '请选择开始时间',
              trigger: 'change'
            }

          ],
          classFinish: [{
              required: true,
              message: '请选择结束时间',
              trigger: 'change'
            }

          ],
          // classTeacher: [{
          //     required: true,
          //     message: '请选择授课教师',
          //     trigger: 'change'
          //   }

          // ],
          remark3: [{
              required: true,
              message: '请选择考勤员',
              trigger: 'change'
            }

          ],


        },
      };
    },
    watch: {




      'classTeacher': {
        handler() {


          if (this.classTeacher.length == 0) {
            this.form.classTeacher = null;
          } else {
            this.form.classTeacher = this.classTeacher.join(',');
          }
        }
      },


      'type_one_date_picker': {
        handler() {
          var allresult = []
          if (this.type_one_date_picker.length != 0) {
            if (this.classWorkOut.length != 0) {

              for (var i = 0; i < this.classWorkOut.length; i++) {
                var xingqi = this.classWorkOut[i];
                // console.log(xingqi);
                var result = this.getAllTuesdays(this.type_one_date_picker[0], this.type_one_date_picker[1], xingqi);

                if (this.form.classCirculate == "隔周循环") {
                  result = this.gezhouxunhuan(result);
                }


                allresult = allresult.concat(result);


              }
              // console.log("type_one_date_picker");
              // console.log(allresult);
              this.one_date_picker_data = allresult
            } else {
              this.one_date_picker_data = null
            }


          }



        }
      },
      'classWorkOut': {
        handler() {
          var allresult = []
          if (this.type_one_date_picker.length != 0) {
            if (this.classWorkOut.length != 0) {

              for (var i = 0; i < this.classWorkOut.length; i++) {
                var xingqi = this.classWorkOut[i];
                // console.log(xingqi);
                var result = this.getAllTuesdays(this.type_one_date_picker[0], this.type_one_date_picker[1], xingqi);

                if (this.form.classCirculate == "隔周循环") {
                  result = this.gezhouxunhuan(result);
                }


                allresult = allresult.concat(result);
                // console.log(allresult);

              }
              this.one_date_picker_data = allresult
            } else {
              this.one_date_picker_data = null
            }


          }



        }
      },
      'form.classCirculate': {
        handler() {
          var allresult = []
          if (this.type_one_date_picker.length != 0) {
            if (this.classWorkOut.length != 0) {

              for (var i = 0; i < this.classWorkOut.length; i++) {
                var xingqi = this.classWorkOut[i];
                // console.log(xingqi);
                var result = this.getAllTuesdays(this.type_one_date_picker[0], this.type_one_date_picker[1], xingqi);

                if (this.form.classCirculate == "隔周循环") {
                  result = this.gezhouxunhuan(result);
                }


                allresult = allresult.concat(result);
                // console.log(allresult);

              }
              this.one_date_picker_data = allresult
            } else {
              this.one_date_picker_data = null
            }


          }



        }
      },

      'type_two_date_picker': {
        handler() {


          if (this.type_two_date_picker.length == 0) {
            this.two_date_picker_data = null;
          } else {
            this.two_date_picker_data = this.type_two_date_picker.join(',');
          }
        }
      },



    },
    created() {
      this.getList();
      this.getTeacherList();
      this.getClassroomList();
      this.getCourseList();
    },
    methods: {
      ChangeClassName(ClassName) {
        const ischoolclass = this.schoolclassList.find(item => item.className == ClassName);
        // console.log(iclassCourse);
        this.form.classId = ischoolclass.id;

      },
      ChangeCourseName(classCourse) {
        const iclassCourse = this.courseList.find(item => item.courseName == classCourse);
        // console.log(iclassCourse);
        this.form.classCourseId = iclassCourse.id;
        this.$set(this.form, 'className', null)


        this.getSchoolclassList(classCourse)
      },

      /** 查询班级列表 */
      getSchoolclassList(classCourse) {
        this.queryParamsSchool.classCourse = classCourse;
        this.queryParamsSchool.deptId = this.$store.state.user.deptId;
        listSchoolclass(this.queryParamsSchool).then(response => {
          this.schoolclassList = response.rows;

        });
      },
      /** 查询课程管理列表 */
      getCourseList() {

        this.queryParamsCourse.deptId = this.$store.state.user.deptId;
        this.queryParamsCourse.courseState = "在开课程";
        listCourse(this.queryParamsCourse).then(response => {
          this.courseList = response.rows;


        });
      },
      getTeacherList() {

        this.queryParamsTeacher.deptId = this.$store.state.user.deptId;

        listUser2(this.queryParamsTeacher).then(response => {
          this.userList = response.rows;
          // console.log(this.userList);

        });
      },
      /** 查询教室列表 */
      getClassroomList() {
        this.queryclassroomParams.deptId = this.$store.state.user.deptId;
        listClassroom(this.queryclassroomParams).then(response => {
          this.classroomList = response.rows;

        });
      },

      changge(type) {

        if (type == 1) {
          this.type = 2;
        } else {
          this.type = 1;
        }

      },

      // 隔周循环就取奇数列
      gezhouxunhuan(arr) {
        // 取奇数列
        // const oddNumbers = arr.filter(num => num % 2 !== 0);

        let oddNumbers = arr.filter(function(elem, index, arr) {
          return index % 2 !== 0;
        });
        return oddNumbers;

      },
      add() {




      },
      open(e1, e2) {
        if (e1 != null) {
          // console.log(e1,e2);
          // this.form.className=null
          this.form.classCourse = e1;
          this.$set(this.form, 'className', null)
          this.form.className = e2;
          this.nodisabled = true;

          // this.getSchoolclassList( this.form.classCourse)
        } else {
          // console.log("2222");
        }

        this.open_scheduling = true;

      },
      /** 查询课程表列表 */
      getList() {
        this.loading = true;
        this.queryParams.deptId = this.$store.state.user.deptId;
        listScheduling(this.queryParams).then(response => {
          this.schedulingList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open_scheduling = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.type_one_date_picker = [];
         this.classWorkOut = [];
        this.type_two_date_picker = [];
        this.classTeacher = [];


        this.form = {
          id: null,
          deptId: null,
          className: null,
          classCourse: null,
          classCapacity: null,
          classAskforleave: null,
          classNoyet: null,
          classWorkOut: null,
          classCirculate: null,
          classStart: null,
          classFinish: null,
          classHours: null,
          classTeacher: null,
          classAttendant: null,
          classRoom: null,
          classStudent: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          schedulingremark: null,
          schedulingremark2: null,
          schedulingremark3: null,
          schedulingremark4: null,
          schedulingremark5: null,
          schedulingremark6: null,
          schedulingremark7: null,
          schedulingremark8: null,
          schedulingremark9: null,
          schedulingremark10: null,
          classId: null,
          studyDate: null,
          week: null,
          state: null,
          reach: null,
          unreach: null,
          askforleave: null,
          attendance: null,
          totalConsumption: null
        };
        this.resetForm("form");
      },
      /** 提交按钮 */
      submitForm() {

        //规则模式
        if (this.type == 1) {

          if (this.one_date_picker_data == null) {
            this.$modal.msgError("请选择日期");
            return;
          }

          this.form.data2 = this.one_date_picker_data.join(',');
        } else {

          //日历模式
          this.form.data2 = this.two_date_picker_data;
        }
        if (this.form.classTeacher == null) {
          this.$modal.msgError("请选择教师");
          return;
        }



        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.deptId = this.$store.state.user.deptId;
            addScheduling(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.$emit('AddSchedulingSuccess', 'AddSchedulingSuccess'); // 触发名为'childEvent'的自定义事件，并传递数据
              this.open_scheduling = false;
              this.reset();
            });

          }
        });
      },


    }
  };
</script>
